<template>
  <div class="drone-video-player">
    <div
      id="drone-video-container"
      ref="videoContainer"
      class="video-container"
    ></div>
    <div v-if="error" class="video-error">
      <i class="el-icon-warning"></i>
      <span>{{ error }}</span>
      <el-button size="small" @click="retry">重试</el-button>
    </div>
    <div v-if="loading" class="video-loading">
      <i class="el-icon-loading"></i>
      <span>{{ loadingText }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import { QNRTPlayer } from "qn-rtplayer-web";

const props = defineProps({
  streamUrl: {
    type: String,
    default: "webrtc://222.222.95.59:1240/shandong/drone001",
  },
  autoplay: {
    type: Boolean,
    default: true,
  },
  muted: {
    type: Boolean,
    default: true,
  },
});

const videoContainer = ref(null);
const player = ref(null);
const error = ref("");
const loading = ref(true);
const loadingText = ref("正在连接视频流...");

const initPlayer = async () => {
  // 销毁现有播放器
  if (player.value) {
    try {
      player.value.destroy();
      console.log("已销毁旧播放器");
    } catch (e) {
      console.error("销毁播放器失败:", e);
    }
    player.value = null;
  }

  error.value = "";
  loading.value = true;
  loadingText.value = "正在初始化播放器...";

  // 解析流地址
  const streamUrl = "webrtc://222.222.95.59:1240/shandong/drone001";

  if (!streamUrl) {
    error.value = "没有可用的视频流地址";
    loading.value = false;
    return;
  }

  console.log("准备播放 WebRTC 流:", streamUrl);

  try {
    // 等待 DOM 渲染
    await nextTick();

    // 确保容器存在
    const container = document.getElementById("drone-video-container");
    if (!container) {
      throw new Error("找不到视频容器元素");
    }

    // 创建七牛云 WebRTC 播放器实例
    player.value = new QNRTPlayer();

    // 初始化配置信息
    const config = {
      autoplay: props.autoplay,
      muted: props.muted,
      controls: true,
      width: "100%",
      height: "100%",
      logLevel: "info", // 日志级别: debug, info, warning, error
      statsReportInterval: 2000, // 统计上报间隔（毫秒）
      // 音频配置
      audio: {
        enable: true,
        sampleRate: 48000,
        channelCount: 2,
      },
      // 视频配置
      video: {
        enable: true,
        width: 1920,
        height: 1080,
        frameRate: 30,
        bitrate: 2000, // kbps
      },
      // 网络配置
      network: {
        reconnect: true, // 自动重连
        reconnectDelay: 3000, // 重连延迟（毫秒）
        maxReconnectAttempts: 5, // 最大重连次数
      },
    };

    // 初始化播放器配置
    player.value.init(config);

    console.log("播放器配置完成，开始播放...");
    loadingText.value = "正在连接视频流...";

    // 开始播放
    await player.value.play(streamUrl, container);
    loading.value = false;
    console.log("播放命令已发送");
  } catch (err) {
    console.error("初始化七牛云播放器失败:", err);
    error.value = `播放器初始化失败: ${err.message || err}`;
    loading.value = false;
  }
};

// 重试播放
const retry = () => {
  console.log("重试播放");
  initPlayer();
};

// 监听流地址变化
watch(
  () => props.streamUrl,
  (newUrl) => {
    if (newUrl) {
      console.log("流地址变更:", newUrl);
      initPlayer();
    }
  }
);

// 生命周期钩子
onMounted(() => {
  console.log("DroneVideoPlayer 组件挂载");
  console.log("视频流地址:", props.streamUrl);
  initPlayer();
});

onUnmounted(() => {
  console.log("DroneVideoPlayer 组件卸载");
  if (player.value) {
    try {
      player.value.destroy();
      console.log("播放器已销毁");
    } catch (e) {
      console.error("销毁播放器失败:", e);
    }
    player.value = null;
  }
});
</script>

<style scoped>
.drone-video-player {
  position: relative;
  width: 100%;
  height: 100%;
  background: #000;
  border-radius: 14px;
  overflow: hidden;
}

.video-container {
  width: 100%;
  height: 100%;
}

#drone-video-container {
  width: 100%;
  height: 100%;
  position: relative;
}

/* 七牛云播放器视频元素样式 */
#drone-video-container video {
  width: 100% !important;
  height: 100% !important;
  object-fit: contain;
  background: #000;
}

.video-error,
.video-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #fff;
  font-size: 14px;
  z-index: 100;
  padding: 20px;
  text-align: center;
  pointer-events: auto;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 8px;
}

.video-error i,
.video-loading i {
  font-size: 32px;
}

.video-error {
  color: #f56c6c;
}

.video-error .el-button {
  margin-top: 10px;
}

.video-loading {
  color: #409eff;
}

.video-loading i {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 七牛云播放器控制栏样式覆盖 */
:deep(.qn-rtplayer-controls) {
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
}

:deep(.qn-rtplayer-loading) {
  background: rgba(0, 0, 0, 0.3);
}

:deep(.qn-rtplayer-error) {
  background: rgba(0, 0, 0, 0.8);
  color: #f56c6c;
}
</style>
